package com.example.springsecuritydemo.entities;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2021-06-24 下午2:14
 */
@Setter
@Getter
public class SecurityUser implements UserDetails {
    private transient User currentUserInfo;
    private List<String> permissionValueList;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new LinkedList<>();
        permissionValueList.forEach(permit -> {
            if (StringUtils.isBlank(permit)) {
                return;
            }
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permit);
            authorities.add(authority);
        });
        return authorities;
    }

    public SecurityUser(User currentUserInfo, List<String> permissionValueList) {
        this.currentUserInfo = currentUserInfo;
        this.permissionValueList = permissionValueList;
    }

    @Override
    public String getPassword() {
        return Objects.isNull(currentUserInfo) ? StringUtils.EMPTY : currentUserInfo.getPassword() + "_" + currentUserInfo.getSalt();
    }

    @Override
    public String getUsername() {
        return Objects.isNull(currentUserInfo) ? StringUtils.EMPTY : currentUserInfo.getLoginName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return "Active".equals(currentUserInfo.getUserState());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return Objects.equals(0, currentUserInfo.getIsDelete());
    }
}
